import { Tab } from "vant";

const Cart = {
  state: {
    cart: JSON.parse(localStorage.getItem('cart')) || [],//购物车数据

  },
  mutations: {
    getCart(state, item) {
      //去重复
      console.log(item)
      var rel = false
      state.cart.forEach((ele) => {
        if (ele.id === item.id) {
          ele.num++;
          rel = true;
        }
      })
      if (!rel) {
        item.num = 1;
        item.checked = false
        state.cart.push(item);
      }
      localStorage.setItem("cart", JSON.stringify(state.cart));
    },
    Cartdel(state, index) {
      //删除
      state.cart.splice(index, 1)
      localStorage.setItem("cart", JSON.stringify(state.cart));
    },
    //单选
    Cartchecked(state, item) {
      state.cart.forEach((ele) => {
        if (ele.id === item.id) {
          ele.checked === item.checked
        }
      })
      localStorage.setItem("cart", JSON.stringify(state.cart));
    },
    //提交订单
     Tab(state,item){
       console.log(item)
     }
  },
  getters: {
    //计算价格
    totalPrice(state) {
      var total = 0;
      state.cart.forEach(ele => {
        if (ele.checked == true) {
          total += ele.originalPrice * ele.num * 100
        }
      })
      return total;
    }
  },
  actions: {
    getCart(content, item) {
      content.commit("getCart", item)
    },
    Cartdel(content, item) {
      content.commit('Cartdel', item)
    },
    Cartchecked(content, item) {
      content.commit('Cartchecked', item)
    },
    Tab(content, item){
      content.commit('Tab', item)
    }


  }
}
export default Cart